<template>
  <view class="black-edit-page">
    <Navbar title="电器管理" />

    <view class="edit-content">
      <!-- 黑名单区域管理 -->
      <view class="area-section">
        <view class="area-header">
          <text class="area-title">黑名单区域管理</text>
          <view class="add-btn-wrap" @click="addBlacklistArea">
            <image
              src="/static/img/minePages/add-btn.png"
              mode="widthFix"
              class="add-btn"
            ></image>
            <text class="add-btn-text">添加</text>
          </view>
        </view>
        <view class="area-list">
          <view v-if="blacklist.length === 0" class="empty-tip">
            <text class="empty-text">暂无黑名单区域</text>
          </view>
          <view class="area-item" v-for="(item, idx) in blacklist" :key="idx">
            <view class="area-name-container">
              <text 
                class="area-name"
                :style="getScrollStyle(item.location, idx)"
              >
                {{ item.location }}
              </text>
            </view>
            <text class="delete-btn" @click="deleteBlacklistArea(idx)"
              >删除</text
            >
          </view>
        </view>
      </view>

      <!-- 白名单区域管理 -->
      <view class="area-section">
        <view class="area-header">
          <text class="area-title">白名单区域管理</text>
          <view class="add-btn-wrap" @click="addWhitelistArea">
            <image
              src="/static/img/minePages/add-btn.png"
              mode="widthFix"
              class="add-btn"
            ></image>
            <text class="add-btn-text">添加</text>
          </view>
        </view>
        <view class="area-list">
          <view v-if="whitelist.length === 0" class="empty-tip">
            <text class="empty-text">暂无白名单区域</text>
          </view>
          <view class="area-item" v-for="(item, idx) in whitelist" :key="idx">
            <view class="area-name-container">
              <text 
                class="area-name"
                :style="getScrollStyle(item.location, idx + 1000)"
              >
                {{ item.location }}
              </text>
            </view>
            <text class="delete-btn" @click="deleteWhitelistArea(idx)"
              >删除</text
            >
          </view>
        </view>
      </view>
    </view>

    <!-- 底部提交按钮 -->
    <view class="action-buttons">
      <view class="action-button delete-button" @click="deleteRule">
        删除
      </view>
      <view
        class="action-button submit-button"
        @click="submit"
        :class="{ disabled: submitting }"
      >
        {{ submitting ? '提交中...' : '提交' }}
      </view>
    </view>
  </view>

  <!-- 区域选择器 -->
  <tn-picker
    v-model:open="showAreaPicker"
    :data="areaPickerData"
    :immediate-change="false"
    :mask="true"
    :show-cancel="false"
    confirm-color="#268EDA"
    label-key="label"
    value-key="value"
    children-key="children"
    @confirm="onAreaConfirm"
  />
</template>

<script setup>
import { ref, computed, onMounted, onUnmounted } from 'vue';
import { onLoad } from '@dcloudio/uni-app';
import Navbar from '@/components/Navbar.vue';
import { createRequest } from '@/utils/request';

// 响应式数据
const blacklist = ref([]);
const whitelist = ref([]);
const showAreaPicker = ref(false);
const areaPickerData = ref([]);
const submitting = ref(false);
const ruleId = ref('');
const currentAddType = ref('');
// 缓存区域选项数据
const cachedAreaData = ref(null);

// 文本滚动相关
const scrollTimers = ref({});
const scrollPositions = ref({});

// 页面加载
onLoad(async options => {
  // 获取父页面传递的id
  if (options.id) {
    ruleId.value = options.id;
    await loadRegionsData();
  } else {
    uni.showToast({
      title: '缺少必要参数',
      icon: 'error',
    });
    setTimeout(() => {
      uni.navigateBack();
    }, 1500);
  }
});

// 页面卸载时清理定时器
onUnmounted(() => {
  Object.values(scrollTimers.value).forEach(timer => {
    if (timer) {
      clearInterval(timer);
    }
  });
});

// 获取文本实际宽度
const getTextWidth = (text) => {
  if (!text) return 0;
  let totalWidth = 0;
  for (let i = 0; i < text.length; i++) {
    const char = text[i];
    if (/[\u4e00-\u9fa5]/.test(char)) {
      totalWidth += 28;
    } else if (/[0-9]/.test(char)) {
      totalWidth += 16;
    } else if (/[-]/.test(char)) {
      totalWidth += 12;
    } else {
      totalWidth += 14;
    }
  }
  return totalWidth;
};

// 判断文本是否超出容器宽度
const isTextOverflow = (text) => {
  const textWidth = getTextWidth(text);
  const containerWidth = 400; // 容器宽度，留出删除按钮的空间
  return textWidth > containerWidth;
};

// 获取滚动样式
const getScrollStyle = (text, index) => {
  if (!text || !isTextOverflow(text)) {
    return {};
  }
  
  return {
    transform: `translateX(${scrollPositions.value[index] || 0}rpx)`,
    transition: 'none'
  };
};

// 开始文本滚动
const startTextScroll = (text, index) => {
  if (!text || !isTextOverflow(text) || scrollTimers.value[index]) {
    return;
  }
  
  const textWidth = getTextWidth(text);
  const containerWidth = 400;
  const scrollDistance = textWidth - containerWidth + 10;
  
  let currentPosition = 0;
  
  scrollTimers.value[index] = setInterval(() => {
    currentPosition -= 1; // 每次移动1rpx
    if (currentPosition <= -scrollDistance) {
      currentPosition = 0; // 重置到开始位置
    }
    
    scrollPositions.value[index] = currentPosition;
  }, 30); // 每30ms更新一次
};

// 停止文本滚动
const stopTextScroll = (index) => {
  if (scrollTimers.value[index]) {
    clearInterval(scrollTimers.value[index]);
    scrollTimers.value[index] = null;
  }
  scrollPositions.value[index] = 0;
};

// 加载区域数据
const loadRegionsData = async () => {
  try {
    uni.showLoading({
      title: '加载中...',
    });

    const result = await createRequest(
      `/blackList/getRegionsByRuleId/${ruleId.value}`,
      {
        method: 'GET',
      }
    );

    // 处理返回的数据
    if (result.data) {
      // 提取黑名单区域的所有信息（原有区域，有ruleRegionId）
      blacklist.value =
        result.data.blacklistRegions?.map(item => ({
          ruleRegionId: item.ruleRegionId,
          regionId: item.regionId,
          location: item.location,
        })) || [];
      // 提取白名单区域的所有信息（原有区域，有ruleRegionId）
      whitelist.value =
        result.data.whitelistRegions?.map(item => ({
          ruleRegionId: item.ruleRegionId,
          regionId: item.regionId,
          location: item.location,
        })) || [];
    }

    console.log('区域数据加载成功:', result);
    
    // 启动文本滚动
    setTimeout(() => {
      blacklist.value.forEach((item, index) => {
        startTextScroll(item.location, index);
      });
      whitelist.value.forEach((item, index) => {
        startTextScroll(item.location, index + 1000);
      });
    }, 500);
  } catch (error) {
    console.error('加载区域数据失败:', error);
    uni.showToast({
      title: error.message || '加载数据失败',
      icon: 'error',
    });
  } finally {
    uni.hideLoading();
  }
};

// 递归解析区域层级数据 - 级联选择器格式
const parseRegionHierarchy = regions => {
  const result = [];

  regions.forEach(region => {
    const item = {
      label: region.regionName,
      value: region.id,
      regionId: region.id,
      regionName: region.regionName,
      regionLevel: region.regionLevel,
    };
    


    // 如果有子区域，递归处理并添加children属性
    if (region.child && region.child.length > 0) {
      item.children = parseRegionHierarchy(region.child);
    }

    result.push(item);
  });

  return result;
};

// 加载区域选项数据
const loadAreaOptions = async () => {
  // 如果已经有缓存数据，直接根据类型赋值给areaPickerData
  if (cachedAreaData.value) {
    if (currentAddType.value === 'blacklist') {
      areaPickerData.value = cachedAreaData.value.blacklist || [];
    } else if (currentAddType.value === 'whitelist') {
      areaPickerData.value = cachedAreaData.value.whitelist || [];
    }
    return;
  }

  try {
    // 使用正确的接口获取区域选项
    const result = await createRequest(
      `/region/getRemainingHierarchyInRules/${ruleId.value}`,
      {
        method: 'GET',
      }
    );

    if (result.data) {
      // 解析白名单选项
      const whitelistOptions = result.data.whitelist
        ? parseRegionHierarchy(result.data.whitelist)
        : [];
      // 解析黑名单选项
      const blacklistOptions = result.data.blacklist
        ? parseRegionHierarchy(result.data.blacklist)
        : [];

      // 保存到缓存对象
      cachedAreaData.value = {
        whitelist: whitelistOptions,
        blacklist: blacklistOptions,
      };

      // 根据当前操作类型设置选择器数据
      if (currentAddType.value === 'blacklist') {
        areaPickerData.value = blacklistOptions;
      } else if (currentAddType.value === 'whitelist') {
        areaPickerData.value = whitelistOptions;
      }
    }
  } catch (error) {
    console.error('加载区域选项失败:', error);
  }
};

// 添加黑名单区域
const addBlacklistArea = async () => {
  currentAddType.value = 'blacklist';
  // 先加载黑名单选项数据
  await loadAreaOptions();
  showAreaPicker.value = true;
};

// 添加白名单区域
const addWhitelistArea = async () => {
  currentAddType.value = 'whitelist';
  // 先加载白名单选项数据
  await loadAreaOptions();
  showAreaPicker.value = true;
};

// 区域选择确认
const onAreaConfirm = selectedItems => {
  if (selectedItems && selectedItems.length > 0) {
    // 级联选择器返回的是value值数组，需要根据这些值查找对应的区域信息
    const currentData = currentAddType.value === 'blacklist' 
      ? cachedAreaData.value?.blacklist 
      : cachedAreaData.value?.whitelist;
    
    // 根据value值递归查找区域信息
    const findRegionPath = (data, values) => {
      let currentLevel = data;
      const path = [];
      
      for (let i = 0; i < values.length; i++) {
        const value = values[i];
        const region = currentLevel.find(item => item.value === value);
        
        if (!region) {
          return null;
        }
        
        path.push(region.label);
        
        if (i < values.length - 1) {
          // 不是最后一个，继续查找子区域
          currentLevel = region.children || [];
        } else {
          // 最后一个，返回完整信息
          return {
            regionId: region.regionId,
            fullPath: path.join('-')
          };
        }
      }
      
      return null;
    };
    
    const regionInfo = findRegionPath(currentData, selectedItems);
    
    if (!regionInfo) {
      uni.showToast({
        title: '区域信息获取失败',
        icon: 'error',
      });
      return;
    }
    
    const regionId = regionInfo.regionId;
    const fullPath = regionInfo.fullPath;

    // 根据当前操作类型添加到对应的列表
    if (currentAddType.value === 'blacklist') {
      // 检查是否已存在相同的regionId
      const exists = blacklist.value.some(item => item.regionId === regionId);
      if (!exists) {
        // 添加到显示数组 - 新增区域没有ruleRegionId，有isWhitelist属性
        blacklist.value.push({
          regionId: regionId,
          location: fullPath, // 显示完整的层级路径
          isWhitelist: false, // 黑名单区域
        });

        // 启动新添加区域的文本滚动
        setTimeout(() => {
          const newIndex = blacklist.value.length - 1;
          startTextScroll(fullPath, newIndex);
        }, 100);

        uni.showToast({
          title: '已添加到黑名单',
          icon: 'success',
        });
      } else {
        uni.showToast({
          title: '该区域已在黑名单中',
          icon: 'none',
        });
      }
    } else if (currentAddType.value === 'whitelist') {
      // 检查是否已存在相同的regionId
      const exists = whitelist.value.some(item => item.regionId === regionId);
      if (!exists) {
        // 添加到显示数组 - 新增区域没有ruleRegionId，有isWhitelist属性
        whitelist.value.push({
          regionId: regionId,
          location: fullPath, // 显示完整的层级路径
          isWhitelist: true, // 白名单区域
        });

        // 启动新添加区域的文本滚动
        setTimeout(() => {
          const newIndex = whitelist.value.length - 1;
          startTextScroll(fullPath, newIndex + 1000);
        }, 100);

        uni.showToast({
          title: '已添加到白名单',
          icon: 'success',
        });
      } else {
        uni.showToast({
          title: '该区域已在白名单中',
          icon: 'none',
        });
      }
    }
  }

  showAreaPicker.value = false;
  currentAddType.value = '';
};

// 删除黑名单区域
const deleteBlacklistArea = async index => {
  const itemToDelete = blacklist.value[index];

  try {
    // 停止该区域的文本滚动
    stopTextScroll(index);
    
    // 检查是否是新增的区域（通过是否有ruleRegionId来判断）
    const isNewArea = !itemToDelete.ruleRegionId;

    if (isNewArea) {
      // 删除新增区域 - 直接从显示数据中删除
      // 从显示数据中删除
      blacklist.value.splice(index, 1);
    } else {
      // 删除原有区域 - 需要发起后端请求，使用URL参数
      const result = await createRequest(
        `/blackList/deleteRegion?ruleRegionId=${itemToDelete.ruleRegionId}&regionId=${itemToDelete.regionId}`
      );
      // 删除成功后从本地数组中移除
      blacklist.value.splice(index, 1);
    }

    uni.showToast({
      title: '删除成功',
      icon: 'success',
    });
  } catch (error) {
    console.error('删除黑名单区域失败:', error);
    uni.showToast({
      title: error.message || '删除失败',
      icon: 'error',
    });
  }
};

// 删除白名单区域
const deleteWhitelistArea = async index => {
  const itemToDelete = whitelist.value[index];

  try {
    // 停止该区域的文本滚动
    stopTextScroll(index + 1000);
    
    // 检查是否是新增的区域（通过是否有ruleRegionId来判断）
    const isNewArea = !itemToDelete.ruleRegionId;

    if (isNewArea) {
      // 删除新增区域 - 直接从显示数据中删除
      // 从显示数据中删除
      whitelist.value.splice(index, 1);
    } else {
      // 删除原有区域 - 需要发起后端请求，使用URL参数
      const result = await createRequest(
        `/blackList/deleteRegion?ruleRegionId=${itemToDelete.ruleRegionId}&regionId=${itemToDelete.regionId}`
      );

      // 删除成功后从本地数组中移除
      whitelist.value.splice(index, 1);
    }

    uni.showToast({
      title: '删除成功',
      icon: 'success',
    });
  } catch (error) {
    console.error('删除白名单区域失败:', error);
    uni.showToast({
      title: error.message || '删除失败',
      icon: 'error',
    });
  }
};

// 提交修改
const submit = async () => {
  if (submitting.value) return;

  submitting.value = true;

  try {
    uni.showLoading({
      title: '提交中...',
    });

    // 构建提交数据 - 只提交新增的区域
    const newRegions = [
      ...blacklist.value
        .filter(item => !item.ruleRegionId)
        .map(item => ({
          regionId: item.regionId,
          location: item.location,
          isWhitelist: false,
        })),
      ...whitelist.value
        .filter(item => !item.ruleRegionId)
        .map(item => ({
          regionId: item.regionId,
          location: item.location,
          isWhitelist: true,
        })),
    ];

    // 如果没有新增区域，直接返回
    if (newRegions.length === 0) {
      uni.showToast({
        title: '提交成功',
        icon: 'success',
      });
      uni.navigateBack();
    }

    const submitData = {
      ruleId: ruleId.value,
      regions: newRegions,
    };

    // 调用添加区域接口
    const result = await createRequest('/blackList/addRuleRegions', {
      method: 'POST',
      data: submitData,
    });

    uni.reLaunch({url: '/pages/index?index=2'});
  } catch (error) {
    console.error('提交失败:', error);
    uni.showToast({
      title: error.message || '提交失败',
      icon: 'error',
    });
  } finally {
    submitting.value = false;
    uni.hideLoading();
  }
};

// 删除规则
const deleteRule = async () => {
  uni.showModal({
    title: '确认删除',
    content: '确定要删除这个规则吗？',
    confirmText: '确认删除',
    cancelText: '取消',
    confirmColor: '#ff4757',
    cancelColor: '#666',
    showCancel: true,
    success: async res => {
      if (res.confirm) {
        try {
          uni.showLoading({
            title: '删除中...',
          });

          // 调用删除规则接口，参考test页面的请求方式
          const result = await createRequest(
            `/blackList/deleteBlackListRule?ruleId=${ruleId.value}`,
            {
              method: 'GET',
            }
          );
          uni.reLaunch({url: '/pages/index?index=2'});
        } catch (error) {
          console.error('删除规则失败:', error);
          uni.showToast({
            title: error.message || '删除失败',
            icon: 'error',
          });
        } finally {
          uni.hideLoading();
        }
      }
    },
  });
};
</script>

<style scoped lang="scss">
.black-edit-page {
  @include page-with-header;
  background: #172869;
  min-height: 100vh;
  display: flex;
  flex-direction: column;
}

.edit-content {
  flex: 1;
  padding: 20rpx 32rpx 0;
  padding-bottom: 160rpx; /* 为固定定位的按钮留出空间 */
}

.area-section {
  margin-bottom: 40rpx;
  border-radius: 10rpx;
  overflow: hidden;
}

.area-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  background: rgba(255, 255, 255, 0.08);
  padding: 0 24rpx;
  height: 80rpx;
}

.area-title {
  color: rgba(255, 255, 255, 0.8);
  font-size: 32rpx;
  font-weight: 500;
}

.add-btn-wrap {
  cursor: pointer;
  display: flex;
  align-items: center;
}

.add-btn {
  width: 28rpx;
  margin-right: 10rpx;
}

.add-btn-text {
  font-size: 28rpx;
  color: #04f7f4;
}

.area-list {
  overflow: hidden;
}

.empty-tip {
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 40rpx 24rpx;
  background: rgba(255, 255, 255, 0.02);
}

.empty-text {
  color: rgba(255, 255, 255, 0.4);
  font-size: 28rpx;
}

.area-item {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0 24rpx;
  height: 80rpx;
  border-bottom: 1rpx solid rgba(255, 255, 255, 0.08);
}

.area-item:last-child {
  border-bottom: none;
}

.area-name-container {
  flex: 1;
  overflow: hidden;
}

.area-name {
  color: rgba(255, 255, 255, 0.8);
  font-size: 28rpx;
  white-space: nowrap;
  display: inline-block;
  min-width: max-content;
}

.delete-btn {
  color: #ff4757;
  font-size: 28rpx;
  font-weight: 500;
  margin-left: 24rpx;
  cursor: pointer;
}

.action-buttons {
  position: fixed;
  bottom: 40rpx;
  left: 24rpx;
  right: 24rpx;
  display: flex;
  justify-content: center;
  gap: 24rpx;
  z-index: 100;
}

.action-button {
  text-align: center;
  line-height: 88rpx;
  border-radius: 44rpx;
  font-size: 30rpx;
  transition: all 0.3s ease;
  height: 88rpx;
}

.delete-button {
  flex: 0.8;
  background: linear-gradient(135deg, #ff4757, #ff3838);
  color: #fff;
  box-shadow: 0 8rpx 24rpx rgba(255, 71, 87, 0.3);
}

.delete-button:active {
  transform: scale(0.98);
  box-shadow: 0 4rpx 12rpx rgba(255, 71, 87, 0.3);
}

.submit-button {
  flex: 1.4;
  background: linear-gradient(135deg, #279bd5, #2264eb);
  color: #fff;
  box-shadow: 0 8rpx 24rpx rgba(30, 200, 225, 0.3);
}

.submit-button:active {
  transform: scale(0.98);
  box-shadow: 0 4rpx 12rpx rgba(30, 200, 225, 0.3);
}

.submit-button.disabled {
  background: rgba(39, 155, 213, 0.5);
  cursor: not-allowed;

  &:active {
    transform: none;
    box-shadow: 0 8rpx 24rpx rgba(30, 200, 225, 0.3);
  }
}

/* Picker组件样式优化 */
:deep(.uni-picker-view-mask) {
  background: transparent !important;
}

:deep(.tn-picker__content) {
  background: #172869 !important;
  border-radius: 20rpx 20rpx 0 0 !important;
}

:deep(.tn-picker__header) {
  background: #172869 !important;
  border-bottom: 1rpx solid rgba(255, 255, 255, 0.1) !important;
}

:deep(.tn-picker__confirm) {
  color: #1ec8e1 !important;
}

:deep(.tn-picker__cancel) {
  color: rgba(255, 255, 255, 0.6) !important;
}

:deep(.tn-picker__title) {
  color: #fff !important;
}

:deep(.tn-picker-view__item) {
  color: #fff !important;
}

:deep(.tn-picker-view__item--selected) {
  color: #1ec8e1 !important;
}
</style>
